import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import qs from "qs";
import { validEmpty } from "@/utils/validate";
import router from "../router/index";

var whiteList = ["/api/getCodePidList.do"];

const service = axios.create({
    // baseURL: "http://192.168.1.109:8080",
    //baseURL: "http://jssggxh.com:8082",
});

service.interceptors.request.use(
    (config) => {
        if (whiteList.indexOf(config.url) < 0) {
            store.dispatch("user/setLoading", true);
        }
        config.data = qs.stringify(config.data);
        if (!validEmpty(getToken())) {
            config.headers.common["token"] = JSON.parse(getToken()).token;
        }
        return config;
    },
    (error) => {
        // do something with request error
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    (response) => {
        const res = response.data;
        store.dispatch("user/setLoading", false);
        if (res.code == 999) {
            MessageBox({
                    title: "提示",
                    message: "您的账号已过期或还没有登录",
                    confirmButtonText: "去登录",
                })
                .then(() => {
                    router.push({
                        path: "/sign",
                        query: { type: 1, loginType: 2 },
                    });
                })
                .catch(() => {
                    console.log("删除成功++++");
                });
            return res;
        } else if (res.code !== 200) {
            const errMsg = res.message || "请求失败";
            Message({
                message: errMsg,
                type: "error",
                duration: 3 * 1000,
            });
            return res;
        } else {
            return res;
        }
    },
    (error) => {
        const { msg } = error;
        store.dispatch("user/setLoading", false);
        Message({
            message: msg || "请求失败",
            type: "error",
            duration: 3 * 1000,
        });
        return Promise.reject(error);
    }
);

export default service;